<script setup lang="ts">
import { typeAll } from '@/api/interface/web/type'
import { validatePlusFloatWithTwo, validatePlusInt } from '@/utils/validate'
import type { FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { productMyList } from '@/api/interface/web/product'

interface Props {
  data?: Record<string, any> | never | null
  status?: string | never | null
}

const { data = null } = defineProps<Props>()

const loading = ref(false)
const typeDatas = ref<any[]>([])

const getLists = async () => {
  loading.value = true
  typeAll({})
    .then((res: any) => {
      typeDatas.value = formatterType(res, '')
    })
    .finally(() => {
      loading.value = false
    })
}

const formatterType = (data: any, parentId: any) => {
  data.forEach((v: any, i: any) => {
    data[i] = {
      label: v.name,
      value: v.id,
      parentId,
      children: formatterType(v.children, v.id),
    }
  })
  return data
}

const seasonDatas = ref([
  {
    label: '春季',
    value: '春季',
  },
  {
    label: '夏季',
    value: '夏季',
  },
  {
    label: '秋季',
    value: '秋季',
  },
  {
    label: '冬季',
    value: '冬季',
  },
])

const sexDatas = ref([
  {
    label: '男性',
    value: '男性',
  },
  {
    label: '女性',
    value: '女性',
  },
  {
    label: '男女性',
    value: '男女性',
  },
])

// const productSizeDatas = ref([
//   {
//     label: 'S',
//     value: 'S',
//   },
//   {
//     label: 'M',
//     value: 'M',
//   },
//   {
//     label: 'L',
//     value: 'L',
//   },
//   {
//     label: 'XL',
//     value: 'XL',
//   },
//   {
//     label: '2XL',
//     value: '2XL',
//   },
//   {
//     label: '3XL',
//     value: '3XL',
//   },
// ])

const baseFormRef = ref()

const form = ref<Record<string, any>>({})

const rules = reactive<FormRules>({
  type: [{ required: true, message: '分类不能为空!', trigger: 'change' }],
  name: [{ required: true, message: '商品不能为空!', trigger: 'blur' }],
  styleCode: [{ required: true, message: '款号不能为空!', trigger: 'blur' }],
  layout: [{ required: true, message: '版型不能为空!', trigger: 'blur' }],
  sex: [{ required: true, message: '性别不能为空!', trigger: 'change' }],
  colorCode: [{ required: true, message: '色号不能为空!', trigger: 'blur' }],
  color: [{ required: true, message: '颜色不能为空!', trigger: 'blur' }],
  productSize: [{ required: true, message: '尺码不能为空!', trigger: 'change' }],
  year: [{ required: true, message: '年份不能为空!', trigger: 'change' }],
  season: [{ required: true, message: '季节不能为空!', trigger: 'change' }],
  cityDate: [{ required: true, message: '上市日期不能为空!', trigger: 'change' }],
  weight: [{ required: true, message: '重量不能为空!', trigger: 'blur' }],
  price: [
    { required: true, message: '吊牌价不能为空!', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!validatePlusFloatWithTwo(value)) {
          callback(new Error('请输入正整数或两位小数!'))
        } else {
          callback()
        }
      },
      trigger: ['blur'],
    },
  ],
  buyingPrice: [
    { required: true, message: '进货价不能为空!', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!validatePlusFloatWithTwo(value)) {
          callback(new Error('请输入正整数或两位小数!'))
        } else {
          callback()
        }
      },
      trigger: ['blur'],
    },
  ],
  inventory: [
    { required: true, message: '库存不能为空!', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!validatePlusInt(value)) {
          callback(new Error('请输入正整数!'))
        } else {
          callback()
        }
      },
      trigger: ['blur'],
    },
  ],
})

const initForm = () => {
  if (data) {
    Object.keys(data).forEach((key: string) => {
      form.value[key] = data![key]
    })

    if (data.secondType) {
      form.value.type = data.secondType
    } else {
      form.value.type = data.firstType
    }
  }
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form.value).forEach((key: string) => {
    if (key == 'type') {
      findTypeData(result, form.value[key], typeDatas.value)
    } else {
      result[key] = form.value[key]
    }
  })
  return result
}

const findTypeData = (result: any, id: any, data: any) => {
  data.forEach((v: any) => {
    if (v.value == id) {
      if (v.parentId) {
        result['type'] = [v.parentId, v.value]
      } else {
        result['type'] = [v.value]
      }
    } else {
      findTypeData(result, id, v.children)
    }
  })
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    baseFormRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm,
})

onMounted(() => {
  getLists()
  initForm()
})

const handleInput = () => {
  dialogInputVisible.value = true
}

const conditionMethod = () => {
  const cond: any = {}
  Object.keys(inputFormSearch.value).map((key) => {
    if (inputFormSearch.value[key] || inputFormSearch.value[key] === 0) {
      if (key === 'type') {
        findSearchTypeData(cond, inputFormSearch.value[key], typeDatas.value)
      } else {
        cond[key] = inputFormSearch.value[key]
      }
    }
  })

  return cond
}
const findSearchTypeData = (result: any, id: any, data: any) => {
  data.forEach((v: any) => {
    if (v.value == id) {
      if (v.parentId) {
        result['firstType'] = v.parentId
        result['secondType'] = v.value
      } else {
        result['firstType'] = v.value
      }
    } else {
      findSearchTypeData(result, id, v.children)
    }
  })
}

const baseTableRef = ref()
const inputFormSearch = ref<any>({})
const handleSearch = () => {
  baseTableRef.value.refresh()
}

const handleResetSearch = () => {
  inputFormSearch.value = {}
  baseTableRef.value.refresh()
}
const dialogInputVisible = ref(false)
const handleInputDialogClose = () => {
  dialogInputVisible.value = false
}
const handleInputRow = (row: any) => {
  row.id = null
  const { firstType, secondType } = row
  if (secondType) {
    row.type = secondType
  } else {
    row.type = firstType
  }
  form.value = row
  dialogInputVisible.value = false
  baseFormRef.value.calling('resetFields')
}
</script>

<template>
  <div v-if="status == 'add'" class="input-box">
    <el-button type="primary" @click="handleInput">智能导入</el-button>
  </div>
  <BaseForm
    ref="baseFormRef"
    :form="form"
    :rules="rules"
    width="320px"
    :attributes="{ 'label-width': '100px' }"
    class="product-form"
  >
    <el-form-item label="分类:" prop="type">
      <el-tree-select
        v-model="form.type"
        :data="typeDatas"
        :render-after-expand="false"
        show-checkbox
        style="width: 240px"
      />
    </el-form-item>

    <el-form-item label="商品名称:" prop="name">
      <el-input
        v-model="form.name"
        type="text"
        placeholder="请输入内容"
        maxlength="20"
        show-word-limit
      >
      </el-input>
    </el-form-item>

    <el-form-item label="款号:" prop="styleCode">
      <el-input
        v-model="form.styleCode"
        type="text"
        placeholder="请输入内容"
        maxlength="20"
        show-word-limit
      >
      </el-input>
    </el-form-item>

    <el-form-item label="版型:" prop="layout">
      <el-input
        v-model="form.layout"
        type="text"
        placeholder="请输入内容"
        maxlength="15"
        show-word-limit
      >
      </el-input>
    </el-form-item>
    <el-form-item label="性别:" prop="sex">
      <el-select v-model="form.sex" placeholder="请选择性别">
        <el-option
          v-for="item in sexDatas"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="色号:" prop="colorCode">
      <el-input
        v-model="form.colorCode"
        type="text"
        placeholder="请输入内容"
        maxlength="10"
        show-word-limit
      >
      </el-input>
    </el-form-item>

    <el-form-item label="颜色:" prop="color">
      <el-input
        v-model="form.color"
        type="text"
        placeholder="请输入内容"
        maxlength="10"
        show-word-limit
      >
      </el-input>
    </el-form-item>

    <!-- <el-form-item label="尺码:" prop="productSize">
      <el-select v-model="form.productSize" placeholder="请选择尺码">
        <el-option
          v-for="item in productSizeDatas"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item> -->
    <el-form-item label="尺码:" prop="productSize">
      <el-input
        v-model="form.productSize"
        type="text"
        placeholder="请输入尺码"
        maxlength="10"
        show-word-limit
      >
      </el-input>
    </el-form-item>

    <el-form-item label="年份:" prop="year">
      <el-date-picker
        v-model="form.year"
        type="year"
        placeholder="请输入年份"
        value-format="YYYY"
      />
    </el-form-item>

    <el-form-item label="季节:" prop="season">
      <el-select v-model="form.season" placeholder="请选择季节">
        <el-option
          v-for="item in seasonDatas"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="上市日期:" prop="cityDate">
      <el-date-picker v-model="form.cityDate" type="date" placeholder="请选择上市日期" />
    </el-form-item>

    <el-form-item label="重量:" prop="weight">
      <el-input
        v-model="form.weight"
        type="text"
        placeholder="请输入重量"
        show-word-limit
        maxlength="15"
      >
      </el-input>
    </el-form-item>

    <el-form-item label="吊牌价:" prop="price">
      <el-input
        v-model="form.price"
        type="text"
        placeholder="请输入吊牌价"
        show-word-limit
        maxlength="11"
      >
      </el-input>
    </el-form-item>

    <el-form-item label="进货价:" prop="buyingPrice">
      <el-input
        v-model="form.buyingPrice"
        type="text"
        placeholder="请输入进货价"
        show-word-limit
        maxlength="11"
      >
      </el-input>
    </el-form-item>

    <el-form-item label="库存:" prop="inventory">
      <el-input
        v-model="form.inventory"
        type="text"
        placeholder="请输入库存"
        show-word-limit
        maxlength="11"
      >
      </el-input>
    </el-form-item>
  </BaseForm>

  <BaseDialog v-model="dialogInputVisible" width="70%">
    <template #buttons>
      <el-button type="info" text bg @click="handleInputDialogClose">取消</el-button>
      <!-- <el-button type="danger" @click="handleInputDialogSubmit">导入</el-button> -->
    </template>

    <div class="form-product-searchbar">
      <el-form :inline="true" :model="inputFormSearch" @submit.prevent>
        <el-form-item label="商品名：">
          <el-input v-model="inputFormSearch.name" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="条形码：">
          <el-input v-model="inputFormSearch.code" placeholder="请输入条形码" />
        </el-form-item>
        <el-form-item label="分类:" prop="type">
          <el-tree-select
            v-model="inputFormSearch.type"
            :data="typeDatas"
            :render-after-expand="false"
            show-checkbox
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="info" text bg @click="handleResetSearch">
            <template #icon>
              <el-icon><Refresh /></el-icon>
            </template>
            重置
          </el-button>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <el-icon><Search /></el-icon>
            </template>
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="history-table" style="overflow-y: auto; height: 50vh">
      <div class="table-wrapper">
        <BaseTable
          ref="baseTableRef"
          :init-table-method="productMyList"
          :condition-method="conditionMethod"
        >
          <el-table-column
            prop="first_name"
            label="一级类目"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="second_name"
            label="二级类目"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column prop="name" label="商品名称" show-overflow-tooltip></el-table-column>
          <el-table-column
            prop="code"
            label="条形码"
            show-overflow-tooltip
            min-width="130"
          ></el-table-column>
          <el-table-column prop="styleCode" label="款号" show-overflow-tooltip></el-table-column>
          <el-table-column prop="layout" label="版型" show-overflow-tooltip></el-table-column>
          <el-table-column prop="sex" label="性别" show-overflow-tooltip></el-table-column>
          <el-table-column prop="colorCode" label="色号" show-overflow-tooltip></el-table-column>
          <el-table-column prop="color" label="颜色" show-overflow-tooltip></el-table-column>
          <el-table-column prop="productSize" label="尺码" show-overflow-tooltip></el-table-column>
          <el-table-column prop="price" label="商品价" show-overflow-tooltip>
            <template #default="scope"> {{ scope.row.price }} 元 </template>
          </el-table-column>
          <el-table-column prop="buyingPrice" label="进货价" show-overflow-tooltip>
            <template #default="scope"> {{ scope.row.buyingPrice }} 元 </template>
          </el-table-column>
          <el-table-column prop="inventory" label="库存" show-overflow-tooltip>
            <template #default="scope"> {{ scope.row.inventory }} </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="handleInputRow(scope.row)">导入</el-button>
            </template>
          </el-table-column>
        </BaseTable>
      </div>
    </div>
  </BaseDialog>
</template>

<style lang="scss">
.input-box {
  width: 100%;
  margin-bottom: 30px;
  box-sizing: border-box;
  display: flex;
  justify-content: flex-end;
}
.product-form {
  width: 100% !important;

  .el-form {
    display: flex;
    flex-wrap: wrap;
    width: 100%;

    .el-form-item {
      width: 50% !important;
    }
  }
}
</style>
